package com.wafersystems.cloud.web.websocket;

import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SocketHandler implements WebSocketHandler {

  public static AtomicInteger onlineNumber = new AtomicInteger();

  public static Vector<WebSocketSession> websocketConnects = new Vector<WebSocketSession>();

  @Override
  public void afterConnectionEstablished(WebSocketSession session) {
    if (null != session && null != session.getAttributes()) {
      // String uniqueId = session.getAttributes().get("uniqueId").toString();
      log.info("有新连接加入！uniqueId:{} 当前在线连接数:{}", session.getId(), onlineNumber.incrementAndGet());
      websocketConnects.add(session);
    }
  }


  @Override
  public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
    log.info("来自客户端消息：{}", message.getPayload());
  }

  @Override
  public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    if (null != session && null != session.getAttributes()) {
      log.warn("有连接error关闭！ 当前连接数:{}", onlineNumber.get());
      log.error(exception.getMessage());
    }
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
    if (null != session && null != session.getAttributes()) {
      log.warn("有连接关闭！ 当前连接数:{}", onlineNumber.decrementAndGet());
      Iterator<WebSocketSession> entries = websocketConnects.iterator();
      while (entries.hasNext()) {
        WebSocketSession entry = entries.next();
        if (session.equals(entry)) {
          log.info("websokect {} is close", entry.getId());
          entries.remove();
          break;
        }
      }
    }
  }

  @Override
  public boolean supportsPartialMessages() {
    log.info("supportsPartialMessages");
    return false;
  }
}
